/*
 * Copyright 2020 wangruiCoder owner
 */

package org.disk.frame.logger.interceptor;

import org.disk.frame.logger.event.HttpLog;
import org.disk.frame.logger.util.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述
 * <p>详细描述</p>
 *
 * @author kyrie 2021/4/23 10:04 上午
 * @since jdk1.8
 */
public class HttpLogInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(HttpLogInterceptor.class);
    private final ThreadLocal<Long> threadLocal = new ThreadLocal<>();
    private final ApplicationContext applicationContext;

    public HttpLogInterceptor(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        threadLocal.set(startTime);
        logger.info("请求：{},开始执行...", request.getRequestURI());
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long startTime = threadLocal.get();
        threadLocal.remove();
        long endTime = System.currentTimeMillis();
        long time = endTime-startTime;

        logger.info("请求：{},执行结束。耗时:{}ms", request.getRequestURI(),  time);
        HttpLog log = new HttpLog(this).remoteIp(IpUtils.getRemoteIp(request))
                .appIp(IpUtils.getLocalIp())
                .appName(applicationContext.getEnvironment().getProperty("spring.application.name"))
                .startTime(startTime)
                .endTime(endTime)
                .time(time)
                .url(request.getRequestURI());
        applicationContext.publishEvent(log);

        String resultCode = MDC.get("resultCode");
        String resultMsg = MDC.get("resultMsg");
        System.out.println(resultCode+"--"+resultMsg);
        MDC.remove("resultCode");
        MDC.remove("resultMsg");

        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
